<?php

namespace app\admin\controller\vv;

use app\common\controller\Backend;
use fast\Tree;

class Category extends Backend
{
    private $tree;
    private $channelList;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wanlshop\Category;
        $this->tree  = Tree::instance();
        $type        = $this->request->request("type");
        if ($type) {
            $this->tree->init(collection($this->model->where('type', $type)->order('weigh desc,id desc')->select())->toArray(), 'pid');
        } else {
            $this->tree->init(collection($this->model->order('weigh desc,id desc')->select())->toArray(), 'pid');
        }
        $this->channelList = $this->tree->getTreeList($this->tree->getTreeArray(0), 'name');
        $this->view->assign("type", $type);
        $this->view->assign("channelList", $this->channelList);
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("flagList", $this->model->getFlagList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            $list = [];
            foreach ($this->channelList as $item) {
                if ($item['type'] == 'goods') {
                    $item['channel'] = $this->tree->getChildrenIds($item['id'], true);
                    $list[]          = $item;
                }
            }
            $list = array_values($list);
            return json([
                "total" => count($list),
                "rows"  => array_values($list)
            ]);
        }
        return $this->fetch();
    }
}